<template>
  <div class="chat-sidebar" style="display: flex; gap: 12px">
    <FosoConversationsList
      ref="agentListRef"
      v-model:active-key="agentChatStore.agentId"
      :request="getMyAgentList"
      :title="$t('customer.chat.customerservice')"
      @itemselect="selectAgent"
      @select-change="agentSelectChange"
    />
    <FosoConversationsList
      :key="customerKey"
      ref="conversationsListRef"
      v-model:active-key="agentChatStore.customerId"
      :is-load-moredata="true"
      :request="getMyCustomerListApi"
      :title="$t('customer.chat.customer')"
      @itemselect="SelectCustomer"
      @select-change="customerSelectChange"
    >
      <template #more-filled>
        <div>
          <TableDotsVertical />
        </div>
      </template>
      <template #menu="{ item, refresh }">
        <CustomerMenu :item="item" :refresh="refresh" />
      </template>
    </FosoConversationsList>
  </div>
</template>

<script setup lang="ts">
import type { agentItem, customerItem } from '../type';

import { TableDotsVertical } from '@vben/icons';

import { getAgentCustomerList, getMyAgentList } from '#/api/agent/bind';
import { getConversationHistory } from '#/api/agent/conversation';
import FosoConversationsList from '#/components/FosoConversationsList/index.vue';
import { useAgentChatStore } from '#/store';

import { BubbleListItemHandle } from './bubbleConfig';
import { CustomerMenu } from './index';

const agentListRef = ref();

const agentChatStore = useAgentChatStore();

// const conversationsListKey = ref();
const conversationsListRef = ref();
// 获取客服列表
const getMyCustomerListApi = (params?: any) => {
  return new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        const result = await getAgentCustomerList({
          agentId: agentChatStore.agentId,
          ...params,
        });
        resolve(result);
      } catch (error) {
        reject(error);
      }
    }, 200);
  });
};
const customerKey = ref(1);
// 点击客服列表
const selectAgent = async (data: agentItem) => {
  // conversationsListKey.value++; // 重新加载列表
  // 先更新客服ID
  agentChatStore.setAgentId(data.key);
  agentChatStore.clearCustomerId();
  // 清空会话列表
  agentChatStore.setConversationList([]);
  // 重新加载客户列表
  conversationsListRef.value.refresh({
    agentId: data.key,
    pp: 666,
  });
  customerKey.value++;
};

// 发送请求获取会话历史
const GetConversationHistory = async (agentId: number, customerId: string) => {
  const res = await getConversationHistory({
    page: 1,
    pageSize: 10,
    agentId,
    customerId,
    conversationId: '1',
  });

  agentChatStore.setHasMoreData(res.hasMoreData);
  // 数据处理

  const newdata = BubbleListItemHandle(res.data);
  // 设置会话数据
  agentChatStore.setConversationList(newdata);
  // 设置客户信息
};

// 点击客户列表
const SelectCustomer = (data: customerItem) => {
  // 设置对话框客户名称
  agentChatStore.setCustomerName(data.label);
};

// 下拉框选择客服更新客户列表
const agentSelectChange = (key: number | string) => {
  agentChatStore.setAgentId(key as number);
  agentChatStore.clearCustomerId();
  conversationsListRef.value.refresh({
    agentId: key,
  });
};

// 下拉框选择客户更新会话历史
const customerSelectChange = (key: number | string) => {
  GetConversationHistory(agentChatStore.agentId, key as string);
};

// 暴露给父组件的方法和属性
defineExpose({
  conversationsListRef,
});

watch(
  // 获取客服列表数据，设置到客户ID
  () => agentListRef.value?.data,
  (newVal) => {
    if (newVal?.length > 0) {
      // 设置客服ID
      agentChatStore.setAgentId(newVal[0].id);
      // 清空客户ID
      agentChatStore.setCustomerId('');
    }
  },
);

// 监听未读消息数量的变化，并更新对应客服与客服消息数量
watch(
  () => agentChatStore.noReadCount,
  (newVal) => {
    if (newVal === 0) return;
    // 找到对应的客户项
    const findCustomerItem = conversationsListRef.value.data.find(
      (item: any) => item.id === agentChatStore.customerId,
    );
    // 客户消息数量相减并更新
    conversationsListRef.value.updatemsgcount(
      findCustomerItem.id,
      findCustomerItem.messageCount - agentChatStore.noReadCount,
    );
    // 找到对应的客服项
    const findAgentItem = agentListRef.value.data.find(
      (item: any) => item.id === agentChatStore.agentId,
    );
    // 客服消息数量相减
    const subcount = findAgentItem.messageCount - agentChatStore.noReadCount;
    // 设置客服消息数量
    agentListRef.value.updatemsgcount(agentChatStore.agentId, subcount);
    // 重置未读数量
    agentChatStore.resetNoReadCount();
  },
);
</script>

<style lang="scss" scoped>
//小屏幕兼容
@media (max-width: 768px) {
  //重新设置侧边栏宽度与高度
  .chat-sidebar {
    width: 500px;
    height: 80px;
    overflow: scroll !important;
  }
  //隐藏列表容器
  .conversations-container {
    display: none !important;
  }
}
// 消息数量提示样式
.message-count {
  position: absolute;
  top: 10%;
  right: 0%;
}
</style>
